/**
 * 如果我們想要進行檔案上傳的動作，則您可以使用實作 org.springframework.web.multipart.MultipartResolver 介面的類別，Spring 提供<br>
 * org.springframework.web.multipart.commons.CommonsMultipartResolver 與 org.springframework.web.multipart.cos.CosMultipartResolver，<br>
 * 分別支援 Commands FileUpload 及 COS FileUpload。<br>
 * FileForm 中接受檔案上傳的屬性型態是 byte 陣列，使用者上傳的檔案可以藉由 org.springframework.web.multipart.support.ByteArrayMultipartFileEditor <br>
 * 將之轉換為 byte 陣列並設定給 FileForm，這必須在定義 Controller 時註冊。
 */

package upload;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.e885.log.E885Logger;

/**
 * @author Eric.Kao(gau168.gau@msa.hinet.net)
 * @version 1.0
 * @company E885 Group
 * @copyright Copyright (c) 2001-2008
 */

public class UploadSimpleFormController extends SimpleFormController
{
	private String path;
	
	static
	{
		E885Logger.testLog.debug( "run UploadSimpleFormController" );
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest,
	 *      org.springframework.web.bind.ServletRequestDataBinder)
	 */
	@Override
	protected void initBinder( HttpServletRequest request, ServletRequestDataBinder binder ) throws Exception
	{
		super.initBinder( request, binder );

		binder.registerCustomEditor( byte[].class, new ByteArrayMultipartFileEditor() );
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(java.lang.Object)
	 */
	@Override
	protected ModelAndView onSubmit( Object command ) throws Exception
	{
		E885Logger.testLog.debug( "execute method onSubmit()" );
		
		FileCommand fileCommand = (FileCommand)command;
		
		String fileName = fileCommand.getName();
		
		E885Logger.testLog.debug( "fileName:[" + fileName + "]" );
		
		if( fileName == null )
			return new ModelAndView( getFormView() );
		
		String storedPath = path + System.getProperty( "file.separator" ) + fileName;
		
		BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( storedPath ) );		
		bos.write( fileCommand.getContents() );
		bos.close();
		
		return new ModelAndView( getSuccessView(), "fileName", fileCommand.getName() );
	}

	/**
	 * @return the path
	 */
	public String getPath()
	{
		return path;
	}

	/**
	 * @param path the path to set
	 */
	public void setPath( String path )
	{
		this.path = path;
	}

}
